
#include "mainlaser.h"
#include "enemies.h"


#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>	// Header File For The OpenGL32 Library

#include "enemyHandlers.h"

Enemy *moreEnemies(int listSize)
{
	Enemy *head = NULL;
	int loop;
	Enemy *tmp;

    for(loop=0; loop<listSize; loop++)
    {
		if ((tmp = malloc(sizeof(*tmp))) == NULL) {
      		printf("failed to alloc memory for enemies\n");
      		(void)exit(EXIT_FAILURE);
    	}

    	tmp->x = 0.0f;
    	tmp->y = 0.0f;
    	
    	tmp->next = head;
    	head = tmp;
    }
    return(head);
}

void enemyDisable(Enemy *toBeRemoved, Enemy *prev)
{
	if(prev==NULL) // head to be removed
		enemies_enabled_head = toBeRemoved->next;
	else
	  prev->next = toBeRemoved->next;
	  
	toBeRemoved->next = enemies_disabled_head;
	enemies_disabled_head = toBeRemoved;
}



Enemy *enemyGetNew(int enemyType)
{
	if(enemies_disabled_head==NULL)
	{
		enemies_disabled_head = moreEnemies(5);
	}
	Enemy *tmp = enemies_enabled_head;
	enemies_enabled_head = enemies_disabled_head;
	enemies_disabled_head = enemies_disabled_head->next;
	enemies_enabled_head->next = tmp;	
	enemies_enabled_head->enemyType = enemyType;
	enemies_enabled_head->counter = 0;
	enemies_enabled_head->currentMode = ENEMY_MODE_NORMAL;
	enemies_enabled_head->health = 100.0f;
	enemies_enabled_head->gunDirection = 0.0f;
	enemies_enabled_head->heading = 0.0f;
	enemies_enabled_head->speed = 0.0f;
	
	switch (enemyType)
	{
		case ENEMY_TYPE_TURRET :
			enemies_enabled_head->handler = handlerTurret;
			break;
		case ENEMY_TYPE_STRIKER :
			enemies_enabled_head->handler = handlerStriker;
			break;
		default:
			printf("no rendered defined for enemy of type %d\n", enemyType);
      		(void)exit(EXIT_FAILURE);
	}
	
	return enemies_enabled_head;
}

void enemiesDrawUpdate()
{
	Enemy *enemy;
	Enemy *prev = NULL;
	enemy = enemies_enabled_head;
	
	while(enemy!=NULL)
	{
		enemy->handler((void *)enemy);
		
		if(enemy->health<0.0f)
			enemy->currentMode = ENEMY_MODE_VANISHED;
		
		if(enemy->y>480.0f)
			enemy->currentMode = ENEMY_MODE_VANISHED;
		
		
		if(enemy->currentMode==ENEMY_MODE_VANISHED)
		{
			enemyDisable(enemy, prev);
			if(prev!=NULL)
	  			enemy = prev->next;
	  		else
	  			enemy = enemies_enabled_head;
		}
		else
		{
			prev = enemy;
	  		enemy = enemy->next;
		}
	}
}




void enemiesInit()
{
	enemies_enabled_head = NULL;
	enemies_disabled_head = moreEnemies(30);
}




